import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:flutter_rfid_dmo/rfid/rfid_connection.dart';
import 'package:flutter_rfid_dmo/rfid/epc_manger.dart';
import 'package:flutter_rfid_dmo/rfid/model/epc_data.dart';
import 'package:flutter_rfid_dmo/rfid/utils/data_convert.dart';
import '../rfid/model/rfid_model.dart';
import 'widget/dialog.dart';

class EPCPage extends StatefulWidget {
  const EPCPage({super.key});

  @override
  State<EPCPage> createState() => _EPCPageState();
}

class _EPCPageState extends State<EPCPage> with AutomaticKeepAliveClientMixin {
  final RFIDConnection _rfidService = RFIDConnection();
  final EpcManager _epcManager = EpcManager();
  List<EpcData> _epcList = [];
  StreamSubscription? _epcSubscription;

  // 区域定义
  // static const int RESERVED_AREA = 0; // 保留区
  // static const int EPC_AREA = 1; // EPC区
  // static const int TID_AREA = 2; // TID区
  // static const int USER_AREA = 3; // User区

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();

    // 订阅EPC数据更新
    _epcList = _epcManager.getAllEpcData();
    _epcSubscription = _epcManager.epcStream.listen((epcList) {
      _epcList = epcList;
      _safeUpdate();
    });
  }

  @override
  void dispose() {
    _epcSubscription?.cancel();
    super.dispose();
  }

  _safeUpdate() {
    if (mounted) {
      // 确保widget还在树中
      setState(() {});
    }
  }

  // 状态变量
  bool isEPCStoreActive = false;
  bool isEPCTidActive = false;
  String selectedType = 'EPC区'; // 默认选择的类型

  Widget _buildRowItem(
    dynamic index,
    dynamic value,
    dynamic count,
  ) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: Row(
        children: [
          SizedBox(
            width: 50, // 设置序号列宽度
            child: Text('$index'),
          ),
          Expanded(
            child: Text('$value'),
          ),
          SizedBox(
            width: 50, // 设置次数列宽度
            child: Text('$count'),
          )
        ],
      ),
    );
  }

  // EPC存盘扫描
  void _toggleEPCStore() {
    setState(() {
      isEPCStoreActive = !isEPCStoreActive;
      _rfidService.uhfSearchTag(!isEPCStoreActive);
    });
  }

  // EPC+TID扫描
  void _toggleEPCTid() {
    setState(() {
      isEPCTidActive = !isEPCTidActive;
      _rfidService.uhfSearchTagTID(!isEPCTidActive);
    });
  }

  _onSelectEPC(BuildContext context, String epc) async {
    String? newEPC = await DialogUtils.showWriteEpcDialog(context, epc);
    if (newEPC != null) {
      await _rfidService.onUHFWritEpc(newEPC);
      _rfidService.clearTag();
    }
  }

  void _showInputDialog(BuildContext context, String epc) {
    _rfidService.selectEPCTag(epc);

    final TextEditingController passwordController =
        TextEditingController(text: '00000000');
    final TextEditingController startAddressController =
        TextEditingController(text: '00');
    final TextEditingController dataLengthController =
        TextEditingController(text: '6');
    final TextEditingController dataController = TextEditingController();
    final List<String> options = ['保留区', 'EPC区', 'TID区', 'User区'];
    int area = EPCType.epc.index; // 默认选择EPC区

    // 写入EPC数据
    Future<void> writeEpcData() async {
      try {
        // 将写入数据转换为字节数组
        // 写入操作
        int offset = int.tryParse(startAddressController.text) ?? 0;
        String data = dataController.text.replaceAll(" ", '');
        if (data.length % 2 == 1) {
          data = "${data}0";
          dataController.text = data;
        }
        if (data.length % 4 != 0) {
          data = "${data}00";
          dataController.text = data;
        }
        dataLengthController.text = "0${data.length ~/ 4}";
        List<int> dataBytes = DataConvert.getStringHex(data);
        List<int> code =
            DataConvert.getStringHex(passwordController.text); // 密码
        // 调用RFID服务写入数据
        await _rfidService.uhfWriteTag(
          area, // 区域
          offset, // 偏移量
          code,
          dataBytes, // 写入数据
        );
        _rfidService.clearTag();
      } catch (e) {
        debugPrint('写入EPC数据失败: $e');
      }
    }

    readTag() async {
      // 读取操作
      int offset = int.tryParse(startAddressController.text) ?? 0;
      int length = int.tryParse(dataLengthController.text) ?? 0;
      dataController.text = '';
      await _rfidService.uhfReadTag(
          area, // 区域
          offset, // 偏移量
          length, // 长度
          DataConvert.getStringHex(passwordController.text));
    }

    StreamSubscription<RfidResult>? msgSub;
    readTag();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, sState) {
            // 只订阅一次
            msgSub ??= _rfidService.resultStream.listen((result) {
              if (result.type == RfidResultType.epcRead &&
                  result.data != null) {
                dataController.text = result.data ?? '';
              }
            });

            return AlertDialog(
              title: const Text('EPC标签读写操作'),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 其它原有输入项
                    Wrap(children: [
                      for (int index = 0; index < options.length; index++)
                        SizedBox(
                          width: 100,
                          child: RadioListTile(
                            dense: true,
                            contentPadding: EdgeInsets.zero,
                            title: Transform.translate(
                              offset: const Offset(-20, 0),
                              child: Text(options[index],
                                  style:
                                      const TextStyle(color: Colors.blueGrey)),
                            ),
                            groupValue: selectedType,
                            value: options[index],
                            activeColor: Colors.green,
                            onChanged: (String? value) {
                              if (value != null) {
                                sState(() {
                                  selectedType = value;
                                  startAddressController.text = '00';
                                  // 更新选中的区域
                                  switch (value) {
                                    case '保留区':
                                      area = EPCType.reserved.index;
                                      dataLengthController.text = '4';
                                      break;
                                    case 'EPC区':
                                      area = EPCType.epc.index;
                                      dataLengthController.text = '0';
                                      break;
                                    case 'TID区':
                                      area = EPCType.tid.index;
                                      dataLengthController.text = '6';
                                      break;
                                    case 'User区':
                                      area = EPCType.user.index;
                                      dataLengthController.text = '4';
                                      break;
                                  }
                                  readTag();
                                });
                              }
                            },
                          ),
                        )
                    ]),
                    TextField(
                      controller: passwordController,
                      decoration: const InputDecoration(labelText: '访问密码'),
                    ),
                    TextField(
                      controller: startAddressController,
                      decoration: const InputDecoration(labelText: '起始地址'),
                    ),
                    TextField(
                      controller: dataLengthController,
                      decoration: const InputDecoration(labelText: '数据长度'),
                    ),
                    TextField(
                      controller: dataController,
                      maxLines: 3,
                      decoration: const InputDecoration(
                        labelText: '数据',
                        hintText: '请输入十六进制数据，如：AA BB CC',
                      ),
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: readTag,
                  child: const Text('读取'),
                ),
                TextButton(
                  onPressed: writeEpcData,
                  child: const Text('写入'),
                ),
              ],
            );
          },
        );
      },
    ).then((_) {
      msgSub?.cancel();
    });
  }

  final regions = ['北美', '中国', '欧洲', '全频段'];
  String dbmStr = '';
  int selectedRegion = 0;
  void _showUHFDialog(BuildContext context) {
    _rfidService.readTxPower();
    int localSelectedRegion = selectedRegion; // 弹框内局部变量
    TextEditingController localDbmCtr = TextEditingController(text: dbmStr);
    StreamSubscription<RfidResult>? msgSub;
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            // 只订阅一次
            msgSub ??= _rfidService.resultStream.listen((msg) {
              if (msg.type == RfidResultType.txPower && msg.data is Map) {
                final obj = msg.data as Map;
                setState(() {
                  localSelectedRegion = obj['regin'] ?? 0;
                  localDbmCtr.text = (obj['dbm'] ?? '33').toString();
                });
              }
            });

            return AlertDialog(
              title: const Center(child: Text('UHF射功率设置')),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      const Text('工作区域'),
                      const SizedBox(width: 16),
                      Expanded(
                        child: DropdownButton<String>(
                          isExpanded: true,
                          value: regions[localSelectedRegion],
                          items: regions
                              .map((e) => DropdownMenuItem(
                                    value: e,
                                    child: Text(e),
                                  ))
                              .toList(),
                          onChanged: (value) {
                            setState(() {
                              localSelectedRegion = regions.indexOf(value!);
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      const Text('发射功率dbm'),
                      const SizedBox(width: 16),
                      Expanded(
                        child: TextField(
                          controller: localDbmCtr,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            hintText: '最大0—33',
                          ),
                          inputFormatters: [
                            FilteringTextInputFormatter.allow(
                                RegExp(r'^([0-9]|[1-2][0-9]|3[0-3]){0,2}')),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    _rfidService.readTxPower();
                  },
                  child: const Text('读取'),
                ),
                TextButton(
                  onPressed: () {
                    _rfidService.writeTxPower(
                        int.tryParse(localDbmCtr.text) ?? 33,
                        localSelectedRegion);
                  },
                  child: const Text('写入'),
                ),
              ],
            );
          },
        );
      },
    ).then((_) {
      // 弹框关闭时自动取消订阅
      msgSub?.cancel();
      // 可选：同步弹框内的值到全局
      selectedRegion = localSelectedRegion;
      dbmStr = localDbmCtr.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用super.build
    return Scaffold(
      body: Column(
        children: [
          _buildRowItem('序号', 'ID编码', '次数'),
          Expanded(
            child: ListView.builder(
              itemCount: _epcList.length,
              itemBuilder: (context, index) {
                var item = _epcList[index];
                return InkWell(
                  onTap: () {
                    // _showInputDialog(context, item.epc);
                    _onSelectEPC(context, item.epc);
                  },
                  child: _buildRowItem(index + 1, item.epc, item.count),
                );
              },
            ),
          ),
          Wrap(
            children: [
              ElevatedButton(
                onPressed: _toggleEPCStore,
                style: ElevatedButton.styleFrom(
                  backgroundColor:
                      isEPCStoreActive ? Colors.orange : null, // 激活状态颜色
                ),
                child: Text(isEPCStoreActive ? '停止' : 'EPC盘存'),
              ),
              ElevatedButton(
                onPressed: _toggleEPCTid,
                style: ElevatedButton.styleFrom(
                  backgroundColor:
                      isEPCTidActive ? Colors.orange : null, // 激活状态颜色
                ),
                child: Text(isEPCTidActive ? '停止' : 'EPC+TID'),
              ),
              ElevatedButton(
                onPressed: () {
                  _showUHFDialog(context);
                },
                child: const Text('设置UHF'),
              ),
              ElevatedButton(
                onPressed: () {
                  _rfidService.clearTag();
                },
                child: const Text('清空'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
